﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using System.IO;
using System.Runtime.Serialization;

namespace Infrastructure.Aspect.Transactions
{
    public class ObjectResourceManager<T> : IEnlistmentNotification 
    {

        private byte[] Previus;
        public T Target { get; set; }
        public T CompleteObject { get; set; }

        #region IEnlistmentNotification Members

        public void Commit(Enlistment enlistment)
        {
            CompleteObject = Target; 
            enlistment.Done();

        }

        public void InDoubt(Enlistment enlistment)
        {
            enlistment.Done();
        }

        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            try
            {
                var ser = new DataContractSerializer(typeof(T));
                var mem = new MemoryStream();
                ser.WriteObject(mem, this.Target);                
                Previus = mem.ToArray(); 
                preparingEnlistment.Prepared();
                mem.Dispose();
            }
            catch 
            {
                preparingEnlistment.ForceRollback();
            }            
        }

        public void Rollback(Enlistment enlistment)
        {
            try
            {
                var mem = new MemoryStream(this.Previus);
                var ser = new DataContractSerializer(typeof(T));
                CompleteObject = (T)ser.ReadObject(mem);
                mem.Dispose();
            }
            catch (Exception)
            {


            }
            finally
            {
                enlistment.Done();
            }
            
            
        }

        #endregion
    }
}
